import { ActionCreatorsMapObject, bindActionCreators } from '@reduxjs/toolkit';
import { capitalize } from '@/helpers/utils.ts';
import { useDispatch } from 'react-redux';
import { useMemo } from 'react';
import { ReduxDispatch } from '@/mySliceCreator.ts';

type ActionsI<Name extends string, T extends ActionCreatorsMapObject> = {
  [K in `use${Capitalize<Name>}Actions`]: () => T;
};

export const useGenerateActions = <
  S,
  T extends ActionCreatorsMapObject,
  Name extends string,
>(
  actions: T,
  name: Name,
) => {
  const key = `use${capitalize(name)}Actions`;

  const useActions = () => {
    const dispatch = useDispatch.withTypes<ReduxDispatch<S>>()();
    return useMemo(() => {
      return bindActionCreators(actions, dispatch);
    }, [dispatch]);
  };

  return {
    [key]: useActions,
  } as ActionsI<Name, T>;
};
